/**
 * 计算多边形面积
 * @param path  [{lat:,lng:}],[{lat:,lng:}],[{lat:,lng:}]
 */
export function calcPolygonArea(path) {
  const radius = 6371009;
  const len = path.length;
  if (len < 3) return 0;
  let total = 0;
  const prev = path[len - 1];
  let prevTanLat = Math.tan((Math.PI / 2 - (prev[1] / 180) * Math.PI) / 2);
  let prevLng = (prev[0] / 180) * Math.PI;
  for (const i in path) {
    const tanLat = Math.tan((Math.PI / 2 - (path[i][1] / 180) * Math.PI) / 2);
    const lng = (path[i][0] / 180) * Math.PI;
    total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);
    prevTanLat = tanLat;
    prevLng = lng;
  }
  return Math.abs(total * (radius * radius));
}
function polarTriangleArea(tan1, lng1, tan2, lng2) {
  const deltaLng = lng1 - lng2;
  const t = tan1 * tan2;
  return 2 * Math.atan2(t * Math.sin(deltaLng), 1 + t * Math.cos(deltaLng));
}
function Area(p0: Array<number>, p1: Array<number>, p2: Array<number>) {
  const area =
    p0[0] * p1[1] +
    p1[0] * p2[1] +
    p2[0] * p0[1] -
    p1[0] * p0[1] -
    p2[0] * p1[1] -
    p0[0] * p2[1];
  return area / 2;
}

/**
 * 计算多边形的中心坐标
 * @param points
 * @return {number[]}
 */
export function getPolygonCentroid(points: Array<Array<number>>) {
  let sum_x = 0;
  let sum_y = 0;
  let sum_area = 0;
  let p1 = points[1];
  for (let i = 2; i < points.length; i++) {
    const p2 = points[i];
    const area = Area(points[0], p1, p2);
    sum_area += area;
    sum_x += (points[0][0] + p1[0] + p2[0]) * area;
    sum_y += (points[0][1] + p1[1] + p2[1]) * area;
    p1 = p2;
  }
  const xx = sum_x / sum_area / 3;
  const yy = sum_y / sum_area / 3;
  return [xx, yy];
}
